package managers.conversationManager.services;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.ResourceBundle;

import managers.DBManager;
import managers.conversationManager.ConversationManager;
import managers.messengerManager.FeedbackManager;
import managers.messengerManager.MessengerManager;
import managers.messengerManager.services.Service;
import utils.StackTracePrinter;

public class PendingMessagesService extends Service {

	public PendingMessagesService() {
		super("Pending Messages", true);
	}


	@Override
	public void run() {

		Statement stmt = null, stmt2 = null;
		ResultSet rs = null;
		
		try {
			stmt = DBManager.getConnection().createStatement();
			stmt2 = DBManager.getConnection().createStatement();
			rs = stmt.executeQuery("select senderid, date, body from spotmessenger.pending_messages where receiverid = "+MessengerManager.getSharedInstance().getUserId());

			while (rs.next()) {
				notifyUser(rs.getInt(1), rs.getTimestamp(2), rs.getBytes(3));
			}
			
			stmt2.executeUpdate("DELETE FROM spotmessenger.pending_messages WHERE receiverid = "+MessengerManager.getSharedInstance().getUserId());
		} catch (SQLException e) {
			MessengerManager.getSharedInstance().getFeedbackManager().updateStatus(
					ResourceBundle.getBundle("managers.conversationManager.services.messages").getString("Error.1"), FeedbackManager.WARNING);
			StackTracePrinter.print(e);
		}
		DBManager.closeResources(stmt, rs);
		DBManager.closeResources(stmt2, null);
	}


	private void notifyUser(int senderId, Date date, byte[] bytes) {
		ConversationManager.getSharedInstance().getUserRequestsManager().requestUserDataAndContactUser(
				MessengerManager.getSharedInstance().getDataManager().getUser(senderId));

		ConversationManager.getSharedInstance().getChatManager().getChat(senderId).updateConversation(bytes, true, date);
		
		

	}

}
